<template>
  <BasicDrawer
    v-bind="$attrs"
    @register="registerDrawer"
    showFooter
    :title="getTitle"
    width="50%"
    @ok="handleSubmit"
  >
    <BasicForm @register="registerForm" />
  </BasicDrawer>
</template>
<script lang="ts">
  import { defineComponent, ref, computed, unref } from 'vue';
  import { BasicForm, useForm } from '/@/components/Form/index';
  import { formSchema } from './websiteArticleTableData';
  import { BasicDrawer, useDrawerInner } from '/@/components/Drawer';
  import { websiteArticleSaveApi,websiteArticleUpdateApi } from '/@/api/website/websiteArticleApi';

  export default defineComponent({
    name: 'WebsiteArticleDrawer.vueDrawer',
    components: { BasicDrawer, BasicForm },
    emits: ['success', 'register'],
    setup(_, { emit }) {
      const isUpdate = ref(true);

      const articleId = ref('');

      const [registerForm, { resetFields, setFieldsValue , validate }] = useForm({
        labelWidth: 150,
        schemas: formSchema,

        showActionButtonGroup: false,
        baseColProps: { lg: 24, md: 24 },
      });

      const [registerDrawer, { setDrawerProps, closeDrawer }] = useDrawerInner(async (data) => {
        resetFields();
        setDrawerProps({ confirmLoading: false });
        isUpdate.value = !!data?.isUpdate;
        articleId.value = data?.data?.articleId;
        if (unref(isUpdate)) {
          if(data.data.coverImage){
            data.data.coverImage = [ data.data.coverImage ];
          }
          if(data.data.files){
            data.data.files = data.data.files.split("#@#");
          }
          setFieldsValue({
            ...data.data,
          });

        }
        /*updateSchema({
          field: 'parentMenu',
          componentProps: {  },
        });*/
      });

      const getTitle = computed(() => (!unref(isUpdate) ? '新增' : '编辑'));

      async function handleSubmit() {
        try {
          const values = await validate();
          values.articleId = articleId.value;
          setDrawerProps({ confirmLoading: true });
          // TODO custom api
          if(values.coverImage)
            values.coverImage = values.coverImage[0];
          if(values.files){
            values.files = values.files.join("#@#");
          }
          console.log(values);
          await (!unref(isUpdate) ? websiteArticleSaveApi(values) : websiteArticleUpdateApi(values));
          closeDrawer();
          emit('success');
        } finally {
          setDrawerProps({ confirmLoading: false });
        }
      }

      return { registerDrawer, registerForm, getTitle, handleSubmit };
    },
  });
</script>
